package com.star.common.notify.factory;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.star.common.notify.config.DingTaskProperties;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * dingtask工厂
 *
 * @author zhouhengzhe #公众号：小白的Java进阶之路
 * @version 1.0
 * @date 2023/6/20 11:03
 */
public class DingTaskFactory {

    private final static String ACCESS_TOKEN_PRE="https://oapi.dingtalk.com/robot/send?access_token=";

    public DingTalkClient dingTalkClient(DingTaskProperties dingTaskProperties) {
        if (StringUtils.isBlank(dingTaskProperties.getAccessToken())
                && StringUtils.isBlank(dingTaskProperties.getSecret())) {
            throw new RuntimeException("access token is null or secret is null");
        }
        return new DefaultDingTalkClient(ACCESS_TOKEN_PRE+dingTaskProperties.getAccessToken()
                + sign(dingTaskProperties.getSecret()));
    }

    public static String sign(String secret) {
        try {
            Long timestamp = System.currentTimeMillis();
            String stringToSign = timestamp + "\n" + secret;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
            return "&timestamp=" + timestamp + "&sign=" + sign;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
